package org.daidai.abstrusewriting.homepage.top.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;

import org.daidai.abstrusewriting.R;

import java.io.IOException;

public class PlayBindService extends Service implements MediaPlayer.OnPreparedListener {

    private MediaPlayer mediaPlayer;
    private String url;

    public PlayBindService() {

    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("PlayBindService", "onCreate: ");
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }


    public class MyBinder extends Binder {
        public void stop() {
            if (mediaPlayer != null) {
                mediaPlayer.pause();
            }
        }

        public void start() {
            if (mediaPlayer != null) {
                mediaPlayer.start();
            }
        }

        public long getCurrentTime() {
            if (mediaPlayer != null) {
                return mediaPlayer.getCurrentPosition();
            }
            return 0;
        }

        public long getDuration() {
            if (mediaPlayer != null) {
                return mediaPlayer.getDuration();
            }
            return 0;
        }

        public void setPosition(int position) {
            if (mediaPlayer != null) {
                mediaPlayer.seekTo(position);
                Log.d("PlayBindService", "setPosition: " + position);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("PlayBindService", "intent == null :" + (intent == null));
        if (intent != null) {

            url = intent.getStringExtra("url");
            if (url != null) {
                final Uri parse = Uri.parse(url);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mediaPlayer = MediaPlayer.create(PlayBindService.this, parse);
                        mediaPlayer.setOnPreparedListener(PlayBindService.this);
                    }
                }).start();
            }
        }
        return new MyBinder();
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
        NotificationManagerCompat.from(this).cancel(998);
        super.onDestroy();
    }
}
